import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';
import localINFO from '@/utils/localInfo';

interface ResetSessionKeysProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const ResetSessionKeys: React.FC<ResetSessionKeysProps> = ({ visible, setVisible }) => {
  const [form] = Form.useForm();

  const queryClient = useQueryClient();

  const ResetSeesionKeys = useMutation({
    mutationFn: (params: any) => api.ClearSessionKey(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('清空会话成功');
      } else {
        message.error(`清空失败,${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('清空会话失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getKeyManageData'] }),
    mutationKey: ['getKeyManageData'],
  });

  const handleDeleteOk = async () => {
    await form.validateFields();
    const password = form.getFieldValue('adminPassword');
    ResetSeesionKeys.mutate({
      password: password,
    });
    form.resetFields();
    setVisible(false);
  };
  const handleDeleteCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="验证管理员密码"
        open={visible}
        onOk={handleDeleteOk}
        onCancel={handleDeleteCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24, marginBottom: 24, width: 450 }}
          autoComplete="off"
        >
          <Form.Item
            label="管理员密码"
            name="adminPassword"
            rules={[{ required: true, message: '请输入管理员密码！' }]}
            style={{ marginBottom: 0 }}
          >
            <Input.Password placeholder="请输入管理员密码" autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ResetSessionKeys;
